<?php

namespace app\api\controller\v2;

use app\api\model\Attention;
use app\api\model\ConfigPersonal;
use app\api\model\GradeNoble;
use app\api\model\GradeStar;
use app\api\model\Labels;
use app\api\model\LabelsUser;
use app\api\model\GradeCharm;
use app\api\model\UserZan;
use app\api\model\UserImg;
use app\api\model\ConfigSystem as Config;
use think\Request;
use think\Db;
use think\Log;
use app\api\model\Blacklist;
use app\api\model\User as UserModel;
use app\api\model\Task;
use app\api\controller\Common;
use app\service\UserIntimate as UserIntimateService;
use app\api\model\SeeRecord;
use app\api\model\UserIntimate;
use app\api\model\PrivatechatDeleTask;
use Vectorface\Whip\Whip;
use GatewayClient\Gateway;
use think\Cache;

class User extends Common
{
    public $params = null;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->params = getRsaPostParamArr2();
    }
    public function indexold()
    {
 
        //人员筛选规则后面统一做了更改 参见L504
        // var_dump($this->MIXparams);exit;
        $entertainment = $this->params['entertainment'] ?? 0;
        $entertainment_child = $this->params['entertainment_child'] ?? '';
        $this->params['active'] = $this->params['avtive'] ?? 0;
        $this->params['id'] = $this->params['id'] ?? '';
        $this->params['age'] = $this->params['age'] ?? '';
        $this->params['sex'] = $this->params['sex'] ?? '';
        $this->params['city'] = $this->params['city'] ?? '';
        $this->params['occupation'] = $this->params['occupation'] ?? '';
        $this->params['stature'] = $this->params['stature'] ?? '';
        $this->params['name'] = $this->params['name'] ?? '';
        $this->params['vip'] = $this->params['vip'] ?? '';
        $this->params['nvshen'] = $this->params['nvshen'] ?? '';
        $this->params['is_identity_authentication'] = $this->params['is_identity_authentication'] ?? '';
        $this->params['star'] = $this->params['star'] ?? '';
        $this->params['online'] = $this->params['online'] ?? '';
        $this->params['fate'] = $this->params['fate'] ?? '';
        $this->params['video_mate'] = $this->params['video_mate'] ?? '';
        $this->params['voice_mate'] = $this->params['voice_mate'] ?? '';
        $this->params['appointment'] = $this->params['appointment'] ?? '';
        $this->params['nearby'] = $this->params['nearby'] ?? '';
        $this->params['attention'] = $this->params['attention'] ?? '';
        $this->params['labels'] = $this->params['labels'] ?? '';
        $this->params['hot'] = $this->params['hot'] ?? '';
        $this->params['new'] = $this->params['new'] ?? '';
        $this->params['select'] = $this->params['select'] ?? '';
        $this->params['privacy'] = $this->params['privacy'] ?? '';
        $this->params['discount'] = $this->params['discount'] ?? 0;
        $this->params['through_membership'] = $this->params['through_membership'] ?? 0;
        $this->params['nation'] = $this->params['nation'] ?? 0;

        $fate_chat = 1;
        $whereFate = '';



        $where_unit = $where = "entertainment = ".$entertainment." and entertainment <> 1 and proxy = 0 and hide_search = 0 and sandbox = 0 and delete_time = 0 and reg = 1 and age >= 18 and quality != 1";

        $config = Config::where(['category' => ['in', ['kefu', 'user', 'privacy']]])->column('title, content');
        
        if (isset($this->params['user_id']) && $this->params['user_id']) {
            $response = UserModel::checkLogin($this->params['user_id']);


            $result = $response->getData();

            if ($result['code'] == 400) {
                return $response;
            }

            $this->member = $result['user'];
            if ($this->member['age'] < 18 || $this->member['entertainment'] == 1) {
                return $this->pass([], 'result');
            }

            $login = 1;

            if($config['id'] == $this->params['user_id']){
                $where = "proxy = 0 and hide_search = 0 and sandbox = 0 and delete_time = 0 and reg = 1";
            }
        } else {
            $login = 0;
        }

        $today_start = date('Y-m-d H:i:s', strtotime(date('Y-m-d')));

        if (empty($this->member['yqr']) && 1==3) {//若无邀请人（上级）展示默认人员
            //$where .= ' and id in (20374698,20375003,20375370,20375631,20376592,20378033,20375635,20378030,20375747,20379407)';
            $dquid=$this->member['id'];
            $where .=" and yqr='' and id not in ($dquid,6382) ";
            $sex = $this->member['sex'] == '男' ? '女' : '男';
            $where .= " and sex = '$sex'";
            $order = ' is_online desc,last_login_datetime desc';
            $page = $this->params['page'] ?? 0;
            $pagesize = $this->params['pagesize'] ?? 10;
            $indexskip = rand(0,10);//选取随机偏移量
        } else {

        if ($login) {
            $blacklist = Blacklist::lists($this->member['id'], false, true);
            if (strtotime($this->member['register_datetime']) > strtotime($config['user_list_hide'])) {
                return $this->pass([]);
            }
            if ($blacklist) {
                $blacklist[] = $config['id'];
            } else {
                $blacklist = [$config['id']];
            }
            
            if ($this->params['attention']) {
                $attention = Attention::lists($this->member['id'], false, true);
                
                $attention_str = implode(',', array_diff($attention, $blacklist));
                $attention_str = $attention_str ?: 0;
                $where .= " and id in ($attention_str)";
            } else {
                $blacklist_str = implode(',', $blacklist);

                // 标签筛选
                if ($this->params['labels']) {
                    $label_ids = explode(',', $this->params['labels']);

                    $user_ids = LabelsUser::where(['types' => 1, 'label_id' => ['in', $label_ids]])->column('user_id');

                    $label_users = implode(',', array_diff($user_ids, $blacklist));
                    $label_users = $label_users ?: 0;

                    $where .= " and id in ($label_users)";
                } else if ($this->params['select']) {
                    $where = "proxy = 0 and hide_search = 0 and sandbox = 0 and delete_time = 0 and reg = 1 and age >= 18 and quality != 1";
                    $selectUsers = Db::name('select_users')
                                    ->alias('a')
                                    ->join('user b', 'a.user_id=b.id')
                                    ->where(['b.age'=>['between', [$this->member['age']-25, $this->member['age']]], 'b.delete_time'=>0,'b.is_banned'=>0])
                                    ->column('a.user_id');
                    if (sizeof($selectUsers)) {
                        $selectUsers_str = implode(',', array_diff($selectUsers, $blacklist));
                        $where .= " and id in ($selectUsers_str)";
                    } else {
                        return $this->pass([]);
                    }
                } else if ($entertainment_child) {
                    $uids = Db::name('user_entertainment_checked')->where(['entertainment_map'=>['in', $entertainment_child]])->column('user_id');
                    $inusers = implode(',', array_diff($uids, $blacklist));
                    $where .= " and id in ($inusers) and shouyi < 100000";
                } else {
                    $where .= " and id not in ($blacklist_str) and shouyi < 100000";
                }
            }

            if (($this->params['hot'] || $this->params['discount']) && !$this->params['age']) {
                if($this->member['age']){
                    if($this->member['sex'] == '男'){
                        $where .= " and age <= " . $this->member['age'];
                        $where_unit .= " and age <= " . $this->member['age'];
                    }else{
                        $where .= " and age <= " . ($this->member['age'] + 10);
                        $where_unit .= " and age <= " . ($this->member['age'] + 10);
                    }
                }
            }
        }


        if ($this->params['id']) {
            $where .= " and id = " . $this->params['id'];
        }

        if ($this->params['age']) {
            if (stripos($this->params['age'], ',') !== false) {
                $age = explode(',', $this->params['age']);
                $where .= " and (age >= " . (intval($age[0]) ?: 18) . " and age <= " . (intval($age[1])??99) . ")";
            } else {
                $where .= " and age > " . $this->params['age'];
            }
        }

        if ($this->params['stature']) {
            if (stripos($this->params['stature'], ',')) {
                $stature = explode(',', $this->params['stature']);
                $where .= " and (stature >= " . intval($stature[0]) . " && stature <= " . intval($stature[1]) . ")";
            } else {
                $where .= " and stature > " . $this->params['stature'];
            }
        }

        $param_sex = $this->params['sex'];
        if ($login && !$param_sex) {
            if ($config['id'] != $this->member['id']) {
                $sex = $this->member['sex'] == '男' ? '女' : '男';
                $where .= " and sex = '$sex'";
            }
            // if (isset($sex) && $sex == '女'){
            //     $where .= " and register_datetime < '$today_start'";
            // }else{
            // }
        } else {
            if ($param_sex && in_array($param_sex, ['男','女'])) {
                $sex = $param_sex;

                $where .= " and sex = '$sex'";

                if ($sex == '男') {
                    $overtopup = Db::name('user_data')->where(['topup'=>['>=', 20000]])->column('user_id');
                    if(sizeof($overtopup)){
                        $where .= " and id not in (" . implode(',', $overtopup) . ")";
                    }
                }
            } else {
                $where .= " and sex = '女'";
            }

        }

        if ($this->params['name']) {
            $where .= " and (name LIKE '%" . $this->params['name'] . "%' or id LIKE '%" . $this->params['name'] . "%')";
        }

        if ($this->params['city']) {
            $where .= " and (city LIKE '" . $this->params['city'] . "%' or notlimit_city <> 0)";
        }

        if ($this->params['occupation']) {
            $where .= " and (occupation = '" . $this->params['occupation'] . "')";
        }

        if ($this->params['active']) {
            if ($this->params['active'] == 1) {
                $where .= " and (is_online = 1)";
            } else if ($this->params['active'] == 2) {
                $where .= " and (is_online = 1 or last_login_datetime >= '".date('Y-m-d H:i:s', strtotime('-72 hour'))."')";
            } else if ($this->params['active'] == 3) {
                $where .= " and (is_online = 1 or last_login_datetime >= '".date('Y-m-d H:i:s', strtotime('-168 hour'))."')";
            }
        // } else if (!$this->params['nearby']){
        //     $uids = Db::name('user')->whereTime('last_login_datetime', '-30 minute')->cache('indexUids:'.date('Y-m-d H:i'),1800)->order(Db::raw('rand()'))->limit(20000)->column('id');
        //     $where .= " and id in (".implode(',', $uids).")";
            // $where .= " and (last_login_datetime >= '".date('Y-m-d H:i:s', strtotime('-24 hour'))."')";
        }



        if ($this->params['vip']) {
            $where .= " and vip_end_datetime > '" . date('Y-m-d H:i:s') . "'";
        }

        if ($this->params['nvshen']) {
            $where .= " and nvshen = 1";
        }

        if (!$this->params['id'] && !$this->params['sex']) {
            $where .= " and home_hidden = 0";
        }

        if ($this->params['is_identity_authentication']) {
            $where .= " and is_identity_authentication = 2";
        }

        if ($this->params['star']) {
            $gradeStar = GradeStar::where(['grade' => $this->params['star']])->find();

            if ($gradeStar) {
                $where .= " and (score >= " . $gradeStar->min . " and score <= " . $gradeStar->max . ")";
            }
        }

        $chat_discount_users = Db::name('act_chat_discount_user')->where(['state'=>0, 'starttime'=>['<=', datetime()], 'endtime'=>['>=', datetime()]])->fetchSql(false)->column('discount','user_id');
        if ($this->params['discount']) {
            if (sizeof($chat_discount_users) == 0) {
                return $this->pass([], 'result');
            }
            $where = $where_unit . ' and sex = "'.($this->member['sex'] == "男"?"女":"男").'" and id in ('. implode(',',array_keys($chat_discount_users)) . ')';
        }

        if ($this->params['through_membership']) {
            $where .= ' and through_membership="'.$this->params['through_membership'].'"';
        }

        if ($this->params['nation']) {
            $where .= ' and nation <> ""';
        }

        $order = '';

        if ($this->params['online']) {
            $order = "is_online desc, ";
        }

        $page = $this->params['page'] ?? 0;
        $pagesize = $this->params['pagesize'] ?? 10;

        if($page == 0){
            Cache::rm(($this->params['user_id']??0) . 'indexskip');
        }
        $indexskip = 0;
        if ($this->params['hot']) {       // 推荐
            if (!$this->params['name'] && !$this->params['city'] && !$this->params['occupation'] && !$this->params['active']) {
                $indexskip = Cache::get(($this->params['user_id']??0) . 'indexskip');
                if(!$indexskip){
                    $indexskip = rand(0,20);
                    Cache::set(($this->params['user_id']??0) . 'indexskip', $indexskip);
                }
            }
            $order .= 'is_online desc, is_recommend desc, case when shouyi<1000 then 0 else 1 end, last_login_datetime desc';
            // $order = 'is_online desc, rand()';
        } elseif($this->params['nearby']){
            $order .= "is_online desc, distance asc, activeval desc, case when shouyi<1000 then 0 else 1 end";
            $where .= ' and city ="' . str_replace('市','',$this->member['city']) . '"';
        } elseif($this->params['new']){
            // return $this->pass([]);
            $where .= ' and register_datetime >="' . date('Y-m-d H:i:s', time() - 7 * 24 * 60 * 60) . '"';
            $order = "id desc";
            // $order = 'is_online desc, rand()';
        } elseif($this->params['select']) {
            $order = "is_online desc, quality desc, last_login_datetime desc";
            // $order = 'is_online desc, rand()';
        } elseif($this->params['discount']) {
            $order = "rand()";
        } else {
            $order .= "sort desc, activeval desc, case when shouyi<1000 then 0 else 1 end, is_online desc, distance asc";
            // $order = 'sort desc, is_online desc, rand()';
        }


        // 今日缘分
        if ($this->params['fate']) {
            $where .= " and role = 0 and yqr = '' and last_login_datetime>'".date('Y-m-d H:i:s', strtotime('-24 hour'))."'";
            $pagesize = 6;

            if($login){

                $cacheFateListKey = 'cacheFateListKey:'.$this->member['id'];
                $fateList = cache($cacheFateListKey)?:[];


                $search_uid = $this->member['id'];
                $sql = "(SELECT * from user_intimate where couple_a like '$search_uid,%' and intimate >= 100) union (SELECT * from user_intimate where couple_b like '$search_uid,%' and intimate >= 100)";
                $userIntimate = Db::query($sql);
    
                if ($userIntimate) {
                    $intimate_uids = [];
                    foreach ($userIntimate as $key => $item) {
                        $intimate_uid = explode(',', $item['couple_a']);
            
                        $intimate_uids[] = $intimate_uid[0] == $search_uid ? $intimate_uid[1] : $intimate_uid[0];
                    }
        
                    $intimate_uids = array_merge($blacklist, $intimate_uids);
                    
                    $where .= ' and id not in ('.implode(',',$intimate_uids).')';
                }

                $hiuids = Db::name('privatechat')->where(['userid'=>$search_uid, 'is_fate'=>1, 'front_id'=>''])->whereTime('addtime', '-8 hour')->column('touserid');

                // $lastChatId_cachekey = 'v2:user:fate_last_chat_id';
                // $last_chat_id = cache($lastChatId_cachekey);
                // if (!$last_chat_id) {
                //     $last_chat_id = Db::name('privatechat')->whereTime('addtime', '-8 hour')->order('id asc')->value('id');
                //     cache($lastChatId_cachekey, $last_chat_id, 7200);
                // }
                // $hiuids = Db::name('privatechat')->where(['id'=>['>=',$last_chat_id], 'is_fate'=>1, 'front_id'=>''])->whereTime('addtime', '-8 hour')->column('touserid');

                if (sizeof($hiuids)) {
                    $hiuids = array_filter(array_merge($hiuids, $fateList));
                    $whereFate = ' and id not in ('.implode(',',$hiuids).')';
                }

                $indexskip = 0;
                if($this->member['sex'] == '女'){
                    $age = $this->member['age'] > 0 ? $this->member['age'] : 0;
                    if($this->member['shouyi'] > 1000){
                        $order = "is_online desc, last_login_datetime desc";
                    }else{
                        $order = "is_online desc, case when volley>200 then 0 else 1 end, last_login_datetime desc";
                    }
                }

            }
        }

        // 语音匹、视频匹配
        if ($this->params['video_mate'] || $this->params['voice_mate']) {
            if ($this->member['age']) {
                $where .= " and (age > " . ($this->member['age'] - 20) . " and age < " . ($this->member['age'] + 20) . ")";
            }

            $ids = Db::name('records_mate')->where(['user_id' => $this->member['id']])->column('to_user');

            if ($ids) {
                $ids = '(' . implode(',', $ids) . ')';
                $where .= ' and id not in ' . $ids;
            }

            $where .= " and is_online = 1 ";
            $indexskip = 0;
            $page = 0;
            $pagesize = 1;
            if ($this->member['sex'] == '男') {
                $order = 'attestation desc, role asc, quality desc, charm_value desc, score desc';
            } else {
                $order = 'attestation desc, role asc, quality desc, noble_grade desc, volley desc';
            }

            if ($this->params['voice_mate']) {
                // 任务
                Task::finish('voice_mate', $this->member['id']);
            } else if ($this->params['video_mate']) {
                // 任务
                Task::finish('video_mate', $this->member['id']);
            }
        }


        // 语音匹、视频匹配
        if ($this->params['privacy']) {
            // return $this->miss('暂停开放，2024-02-01后重新开放');
            $hasPrivacyAccount = Db::name('user')->where(['reg'=>2, 'authcode'=>$this->member['id']])->find();
            if (!$hasPrivacyAccount) {
                return $this->miss('未创建私密电台账号');
            }
            $where .= " and last_login_datetime>'".date('Y-m-d H:i:s', strtotime('-10 minute'))."'";
            if ($this->member['age']) {
                if ($this->member['sex'] == '女') {
                    $where .= " and age between " . $this->member['age'] . " and " . ($this->member['age'] + 25);
                } else {
                    $where .= " and age between " . ($this->member['age'] - 25) . " and " . $this->member['age'];
                }
            }

            $blacklist = Blacklist::lists($hasPrivacyAccount['id'], true);
            if ($blacklist) {
                $where .= " and id not in ($blacklist)";
            }
            $where = str_replace('and reg = 1', '', $where);

            $where .= " and is_online = 1 and reg=2 and authcode!=''";
            $indexskip = 0;
            $page = 0;
            $pagesize = 1;
            $order = 'last_login_datetime desc';

            $todayMatchNum = Db::name('privacy_chat_records')->where(['userid'=>$this->member['id']])->whereTime('create_time','today')->count();
            $isVip = 0;
            if ($this->member['noble_grade'] && $this->member['noble_time'] > time()) {
                $privilege = Db::name('grade_noble')->where(['grade' => $this->member['noble_grade']])->value('privilege');
                $privilege = explode(',', $privilege);
                if (in_array(19, $privilege)) {
                    $isVip = 1;
                }
            }
            $privacy_match_keys = ['privacy_match_daynum', 'privacy_match_daynum_vip'];
            if ($config[$privacy_match_keys[$isVip]] <= $todayMatchNum) {
                return $this->miss('今日匹配次数已用完', $isVip?400:203);
            }
        }

        if ($this->params['appointment']) {
            $ids = ConfigPersonal::where(['video_switch' => 1])->column('user_id');

            $ids = $ids ? '(' . implode(',', $ids) . ')' : '(0)';
            $where .= ' and is_online = 1 and id in' . $ids;
        }
        }        
        
        $num = 0;
        for ($i = 0; $i < 1; $i++) {
            $num++;
            $distance_sql = distance(($this->params['latitude']??0), ($this->params['longitude']??0));

            if (!$fate_chat) {
                $whereFate = '';
            }

            $field = 'id user_id, name user_name, head_portrait user_head, sex user_sex, age user_age, city,
                img_auth, is_online, is_identity_authentication, last_login_datetime, nvshen, hide_online_time,
                noble_grade, noble_time, hide_distance, kejian, xuni_discount, notlimit_city, role, voice,
                voice_time, voice_auth,offten_city, realname_auth, register_datetime, yqr, occupation, auth_tag, entertainment,self_slogan,entertainment_child,is_banned,through_membership,nation,latitude,longitude,stature';
                
            // if($this->member['sex'] == '女' && $this->params['hot']==1){//女用户首页推荐加权按男在线土豪值排序
            //     $order = '(is_online * 50000) + tycoon DESC';
            //     $indexskip=rand(0,5);
            // }
            //后来统一更改显示原则
            $sex = $this->member['sex'] == '男' ? '女' : '男';
            $where = " 1=1 and sex = '$sex' and reg=1 and id not in (6382) ";
            //如果用户被禁言 则不允许展示
            $limit_chat = Db::name('limit_chat')->order('time desc')->column('user_id');
            $where .= " and id not in (" . implode(',', $limit_chat) . ") ";
            if (empty($this->member['yqr'])) {//若无邀请人（上级）也默认展示无邀请人的人员
                $where .=" and yqr='' ";
            }else{
                $where .=" and yqr!='' ";
            }
            $whereFate='';
            $order = " is_online desc,last_login_datetime desc,tycoon desc";
            $indexskip=rand(0,10);//控制跳页
            //$indexskip=0;
            $sql = "select distinct $field, $distance_sql from user where $where $whereFate group by user_id order by $order limit " . ($page * $pagesize + $indexskip) . ", $pagesize";
            // var_dump($sql);exit;
            // $date = date('Y-m-d H:i:s');
            // file_put_contents("./log.txt","[$date] ".$sql. PHP_EOL,FILE_APPEND);
            try {
                $data = Db::query($sql);
            } catch (\Exception $e) {
                Log::write($e->getMessage(), 'error');
                return $this->miss('查询发生异常');
            }

            if (sizeof($data)) {
                if ($page && ($this->params['hot'] || $this->params['nearby']) && count($data) < $pagesize) {
                    $page = 0;
                    $i = -1;
                } else {
                    if ($this->params['video_mate'] || $this->params['voice_mate']) {
                        Db::name('records_mate')->insert(['user_id' => $this->member['id'], 'to_user' => $data[0]['user_id'], 'create_time' => time()]);
                    }

                    //$gradeNoble = GradeNoble::where(['id' => ['gt', 0]])->cache(86400)->column('id, icon, circle');
                    $gradeNoble = GradeNoble::where(['id' => ['gt', 0]])->cache(30)->column('id, icon, circle');
                    $ids = array_column($data, 'user_id');

                    $user_labels = Labels::lists($ids);
    
                    $car_ids = Db::name('user_car')->where(['user_id' => ['in', $ids], 'expire' => ['gt', time()], 'is_select' => 1])->column('user_id, car_id');
                    if ($car_ids) {
                        $car_covers = Db::name('car')->where(['id' => ['in', $car_ids]])->cache(86400)->column('id, cover');
                    } else {
                        $car_covers = [];
                    }
    
                    $photo_uids = [];
                    $photos = [];
                    foreach ($data as $key => $item) {
                        if ($item['voice_auth'] != 2 || !$item['voice']|| !$item['voice_time']) {
                            $photo_uids[] = $item['user_id'];
                        }
                    }
                    
                    if ($photo_uids) {
                        $userImgs = UserImg::where(['types' => 1, 'user_id' => ['in', $photo_uids], 'burn' => 0, 'packet' => 0, 'is_auth' => 0, 'is_avatar' => 0, 'status' => 1])->order('id desc')->cache(7200)->select();
                        $photos = [];
                        foreach ($userImgs as $img) {
                            if (!isset($photos[$img['user_id']]) || count($photos[$img['user_id']]) < 4) {
                                $pic = json_decode($img['picthumb'], true);
                                if (isset($pic[0])) {
                                    $photos[$img['user_id']][] = changeUrl($pic[0]);
                                }
                            }
                        }
                    }


        
                    $timenow = time();
                    foreach ($data as $key => $item) {
                         $data[$key]['city'] =$item['offten_city'];
                        //是否打过招呼  1是  0否
                        $is_say_hello = cache('greet'.$this->member['id'].'-to-' . $item['user_id']);
                        if ($is_say_hello){
                            $data[$key]['is_say_hello'] =1;
                        }else{
                            $data[$key]['is_say_hello'] =0;
                        }
                        if (!$this->params['video_mate'] && !$this->params['voice_mate'] && !$this->params['fate']) {
                            if (isset($car_ids[$item['user_id']]) && isset($car_covers[$car_ids[$item['user_id']]])) {
                                $data[$key]['car_cover'] = changeUrl($car_covers[$car_ids[$item['user_id']]]);
                            } else {
                                $data[$key]['car_cover'] = '';
                            }
                        }

                        $data[$key]['is_vip'] = $item['noble_grade'] && $item['noble_time'] > time() ? 1 : 0;
                        $data[$key]['is_new'] = (strtotime($item['register_datetime']) + 86400) > time() ? 1 : 0;

                        $data[$key]['user_distance'] = '';
                        if ($item['hide_distance']) {
                            $data[$key]['user_distance'] = '保密';
                        } else if ($item['latitude'] && $item['longitude']){
                            $distance = $item['xuni_discount'] + 0 ? $item['xuni_discount'] : $item['distance'];
                            $data[$key]['user_distance'] = $distance >= 1000 ? number_format(($distance / 1000), 1) . 'km' : number_format($distance, 1) . 'm';
                        }

                        if (!$this->params['nearby']) {
                            $data[$key]['user_distance'] = '';
                        }

                        $last_login_datetime = strtotime($item['last_login_datetime']);
                        // if ($item['is_online'] == 0) {
                        //     if ($timenow - 3*86400 < $last_login_datetime) {
                        //         $data[$key]['is_online'] = 1;
                        //     }
                        // }
                        if ($item['is_banned']) {
                            $data[$key]['is_online'] = 0;
                        }

                        if ($data[$key]['is_online']) {
                            $data[$key]['last_login_datetime'] = $timenow - $last_login_datetime < 1800 ? '在线' : (substr($data[$key]['user_id'], -1) + 1 + substr($timenow, -3, 1)).'分钟前在线';
                        } else {
                            $data[$key]['last_login_datetime'] = '';
                        }

                        if ($item['noble_grade'] && $item['noble_time'] > time()) {
                            $data[$key]['noble_icon'] = $gradeNoble[$item['noble_grade']] ? $gradeNoble[$item['noble_grade']]['icon'] : '';
                            $data[$key]['noble_circle'] = $gradeNoble[$item['noble_grade']] ? $gradeNoble[$item['noble_grade']]['circle'] : '';
                        } else {
                            $data[$key]['noble_icon'] = '';
                            $data[$key]['noble_circle'] = '';
                        }

                        $data[$key]['voice'] = '';
    
                        if ($item['voice_auth'] != 2 || !$item['voice']|| !$item['voice_time']) {
                            $data[$key]['photos'] = $photos[$item['user_id']] ?? [];
                        } else {
                            $data[$key]['photos'] = [];
                        }

                        $labels = $user_labels[$item['user_id']] ?? [];
                        $data[$key]['labels'] = array_slice($labels, 0, 5);


                        $data[$key]['entertainment_text'] = Db::name('user_entertainment')->where(['role_type'=>$data[$key]['entertainment']])->value('name');
                        if ($data[$key]['entertainment_child']) {
                            $additionValue = 1;
                            $numbersArray = explode(',', $data[$key]['entertainment_child']);
                            $resultArray = array_map(function ($number) use ($additionValue) {
                                return $number + $additionValue;
                            }, $numbersArray);
                            $resultString = implode(',', $resultArray);

                            $data[$key]['entertainment_child_text'] = Db::name('user_entertainment')->where(['id'=>['in',$resultString]])->column('name');
                            $data[$key]['entertainment_child_text'] = implode('|',$data[$key]['entertainment_child_text']);
                        }

                        $data[$key]['is_chat_discount'] = false;
                        if (isset($chat_discount_users[$data[$key]['user_id']])) {
                            $data[$key]['is_chat_discount'] = (floatval($chat_discount_users[$data[$key]['user_id']]) / 10) . '折';
                        }
                        
                        $isHide = ConfigPersonal::where('user_id', $item['user_id'])->value('is_hide');
                        $data[$key]['is_hide'] = is_null($isHide) ? 0 : $isHide;

                        unset($data[$key]['img_auth'], $data[$key]['xuni_discount'],$data[$key]['noble_grade'], $data[$key]['noble_time'],
                            $data[$key]['notlimit_city'], $data[$key]['distance'], $data[$key]['register_datetime'], $data[$key]['role'], $data[$key]['hide_online_time'], $data[$key]['voice_auth']);
                        unset($data[$key]['yqr'], $data[$key]['latitude'], $data[$key]['longitude']);
                    }
                }
            } else {
                $data = [];

                if ($page && ($this->params['hot'] || $this->params['nearby'])) {
                    $page = 0;
                    $i = -1;
                } else if ($page == 0 && $num == 1) {
                    $indexskip = 0;
                    $i = -1;
                } else {
                    if ($this->params['fate']) {
                        $fate_chat = 0;
                    }
                    if ($this->params['video_mate'] || $this->params['voice_mate']) {
                        Db::name('records_mate')->where(['user_id' => $this->member['id']])->delete();
                    }
                }
            }
        }

        if (sizeof($data)) {
            $uids = array_column($data, 'user_id');
            if ($this->params['fate']) {
                $fateList = array_merge($fateList, $uids);
                cache($cacheFateListKey, $fateList, 600);
            }
        }

        if ($this->member && $this->member['sex'] == '男') {
            action('api/Login/systemPushLianmaiMale');
        }
        if (sizeof($data) && $this->params['privacy']) {
            Db::name('privacy_chat_records')->insert(['userid'=>$this->member['id'], 'touserid'=>$data[0]['user_id'], 'create_time'=>time()]);
        }
        return $this->pass($data, 'result');
        // return $this->pass(base64_encode(json_encode($data, JSON_UNESCAPED_UNICODE)), 'result');
    }
        public function index()
    {
        
        //人员筛选规则后面统一做了更改 参见L504
        // var_dump($this->MIXparams);exit;
        $entertainment = $this->params['entertainment'] ?? 0;
        $entertainment_child = $this->params['entertainment_child'] ?? '';
        $this->params['active'] = $this->params['avtive'] ?? 0;
        $this->params['id'] = $this->params['id'] ?? '';
        $this->params['age'] = $this->params['age'] ?? '';
        $this->params['sex'] = $this->params['sex'] ?? '';
        $this->params['city'] = $this->params['city'] ?? '';
        $this->params['occupation'] = $this->params['occupation'] ?? '';
        $this->params['stature'] = $this->params['stature'] ?? '';
        $this->params['name'] = $this->params['name'] ?? '';
        $this->params['vip'] = $this->params['vip'] ?? '';
        $this->params['nvshen'] = $this->params['nvshen'] ?? '';
        $this->params['is_identity_authentication'] = $this->params['is_identity_authentication'] ?? '';
        $this->params['star'] = $this->params['star'] ?? '';
        $this->params['online'] = $this->params['online'] ?? '';
        $this->params['fate'] = $this->params['fate'] ?? '';
        $this->params['video_mate'] = $this->params['video_mate'] ?? '';
        $this->params['voice_mate'] = $this->params['voice_mate'] ?? '';
        $this->params['appointment'] = $this->params['appointment'] ?? '';
        $this->params['nearby'] = $this->params['nearby'] ?? '';
        $this->params['attention'] = $this->params['attention'] ?? '';
        $this->params['labels'] = $this->params['labels'] ?? '';
        $this->params['hot'] = $this->params['hot'] ?? '';
        $this->params['new'] = $this->params['new'] ?? '';
        $this->params['select'] = $this->params['select'] ?? '';
        $this->params['privacy'] = $this->params['privacy'] ?? '';
        $this->params['discount'] = $this->params['discount'] ?? 0;
        $this->params['through_membership'] = $this->params['through_membership'] ?? 0;
        $this->params['nation'] = $this->params['nation'] ?? 0;

        $fate_chat = 1;
        $whereFate = '';



       // $where_unit = $where = "entertainment = ".$entertainment." and entertainment <> 1 and proxy = 0 and hide_search = 0 and sandbox = 0 and delete_time = 0 and reg = 1 and age >= 18 and quality != 1";
          $where_unit = $where = "entertainment = ".$entertainment." and entertainment <> 1 and proxy = 0 and hide_search = 0 and sandbox = 0 and delete_time = 0 and reg = 1  and quality > 1";

        // $config = Config::where(['category' => ['in', ['kefu', 'user', 'privacy']]])->column('title, content');
        
        if (isset($this->params['user_id']) && $this->params['user_id']) {
            $response = UserModel::checkLogin($this->params['user_id']);


            $result = $response->getData();

            if ($result['code'] == 400) {
                return $response;
            }

            $this->member = $result['user'];
            if ($this->member['age'] < 18 || $this->member['entertainment'] == 1) {
                return $this->pass([], 'result');
            }

            $login = 1;

            // if($config['id'] == $this->params['user_id']){
            //     $where = "proxy = 0 and hide_search = 0 and sandbox = 0 and delete_time = 0 and reg = 1";
            // }
        } else {
            $login = 0;
        }

        $today_start = date('Y-m-d H:i:s', strtotime(date('Y-m-d')));

        // if (empty($this->member['yqr']) && 1==3) {//若无邀请人（上级）展示默认人员
        //     //$where .= ' and id in (20374698,20375003,20375370,20375631,20376592,20378033,20375635,20378030,20375747,20379407)';
        //     $dquid=$this->member['id'];
        //     $where .=" and yqr=''";
        //     $sex = $this->member['sex'] == '男' ? '女' : '男';
        //     $where .= " and sex = '$sex'";
        //     $order = ' is_online desc,last_login_datetime desc';
        //     $page = $this->params['page'] ?? 0;
        //     $pagesize = $this->params['pagesize'] ?? 10;
        //     $indexskip = rand(0,10);//选取随机偏移量
        // } else {

        // if ($login) {
        //     $blacklist = Blacklist::lists($this->member['id'], false, true);
        //     if (strtotime($this->member['register_datetime']) > strtotime($config['user_list_hide'])) {
        //         return $this->pass([]);
        //     }
        //     if ($blacklist) {
        //         $blacklist[] = $config['id'];
        //     } else {
        //         $blacklist = [$config['id']];
        //     }
            
            
            
        //     if(!empty($blacklist_str)){
        //          $where .= " and id not in ($blacklist_str) and shouyi < 100000";
        //     }
            
        //     if (($this->params['hot'] || $this->params['discount']) && !$this->params['age']) {
        //         if($this->member['age']){
        //             if($this->member['sex'] == '男'){
        //                 $where .= " and age <= " . $this->member['age'];
        //                 $where_unit .= " and age <= " . $this->member['age'];
        //             }else{
        //                 $where .= " and age <= " . ($this->member['age'] + 10);
        //                 $where_unit .= " and age <= " . ($this->member['age'] + 10);
        //             }
        //         }
        //     }
        // }



        // if ($this->params['age']) {
        //     if (stripos($this->params['age'], ',') !== false) {
        //         $age = explode(',', $this->params['age']);
        //         $where .= " and (age >= " . (intval($age[0]) ?: 18) . " and age <= " . (intval($age[1])??99) . ")";
        //     } else {
        //         $where .= " and age > " . $this->params['age'];
        //     }
        // }else{
        //     $where .= " and age > 18 " ; 
        // }

        // $param_sex = $this->params['sex'];
        // if ($login && !$param_sex) {
        //     if ($config['id'] != $this->member['id']) {
        //         $sex = $this->member['sex'] == '男' ? '女' : '男';
        //         $where .= " and sex = '$sex'";
        //     }
        //     // if (isset($sex) && $sex == '女'){
        //     //     $where .= " and register_datetime < '$today_start'";
        //     // }else{
        //     // }
        // } else {
        //     if ($param_sex && in_array($param_sex, ['男','女'])) {
        //         $sex = $param_sex;

        //         $where .= " and sex = '$sex'";

        //         // if ($sex == '男') {
        //         //     $overtopup = Db::name('user_data')->where(['topup'=>['>=', 20000]])->column('user_id');
        //         //     if(sizeof($overtopup)){
        //         //         $where .= " and id not in (" . implode(',', $overtopup) . ")";
        //         //     }
        //         // }
        //     } else {
        //         $where .= " and sex = '女'";
        //     }

        // }


        // $order = '';

        // $page = $this->params['page'] ?? 0;
        // $pagesize = $this->params['pagesize'] ?? 10;

        // if($page == 0){
        //     Cache::rm(($this->params['user_id']??0) . 'indexskip');
        // }
        // $indexskip = 0;
        // if ($this->params['hot']) {       // 推荐
        //     if (!$this->params['name'] && !$this->params['city'] && !$this->params['occupation'] && !$this->params['active']) {
        //         $indexskip = Cache::get(($this->params['user_id']??0) . 'indexskip');
        //         if(!$indexskip){
        //             $indexskip = rand(0,20);
        //             Cache::set(($this->params['user_id']??0) . 'indexskip', $indexskip);
        //         }
        //     }
        //     $order .= 'is_online desc, is_recommend desc, case when shouyi<1000 then 0 else 1 end, last_login_datetime desc';
        //     // $order = 'is_online desc, rand()';
        // }else {
        //     $order .= "sort desc, activeval desc, case when shouyi<1000 then 0 else 1 end, is_online desc, distance asc";
        //     // $order = 'sort desc, is_online desc, rand()';
        // }

        // }        
        
        
        $page = $this->params['page'] ?? 0;
        $pagesize = $this->params['pagesize'] ?? 10;
        $num = 0;
        for ($i = 0; $i < 1; $i++) {
            $num++;
            $distance_sql = distance(($this->params['latitude']??0), ($this->params['longitude']??0));

            if (!$fate_chat) {
                $whereFate = '';
            }

            $field = 'id user_id, name user_name, head_portrait user_head, sex user_sex, age user_age, city,
                img_auth, is_online, is_identity_authentication, last_login_datetime, nvshen, hide_online_time,
                noble_grade, noble_time, hide_distance, kejian, xuni_discount, notlimit_city, role, voice,
                voice_time, voice_auth,offten_city, realname_auth, register_datetime, yqr, occupation, auth_tag, entertainment,self_slogan,entertainment_child,is_banned,through_membership,nation,latitude,longitude,stature';
                
            //后来统一更改显示原则
            $sex = $this->member['sex'] == '男' ? '女' : '男';
            $where = "sex = '$sex' and reg=1 and hide_search = 0 and forbidden_speech=0 and forbidden_speech=0 and delete_time=0  ";
            //如果用户被禁言 则不允许展示
            // $limit_chat = Db::name('limit_chat')->order('time desc')->column('user_id');
            // $where .= " and id not in (" . implode(',', $limit_chat) . ") ";
            if (empty($this->member['yqr'])) {//若无邀请人（上级）也默认展示无邀请人的人员
                $where .=" and yqr='' ";
            }else{
                 $where .=" and yqr >0 ";
            }
            $whereFate='';
            $order = " is_online desc,last_login_datetime desc,tycoon desc";
            $indexskip=rand(0,10);//控制跳页
            //$indexskip=0;
            $sql = "select distinct $field, $distance_sql from user where $where group by user_id order by $order limit " . ($page * $pagesize + $indexskip) . ", $pagesize";
            // var_dump($sql);exit;
            // $date = date('Y-m-d H:i:s');
            // file_put_contents("./log.txt","[$date] ".$sql. PHP_EOL,FILE_APPEND);
            try {
                $data = Db::query($sql);
            } catch (\Exception $e) {
                Log::write($e->getMessage(), 'error');
                return $this->miss('查询发生异常');
            }

            if (sizeof($data)) {
                if ($page && ($this->params['hot'] || $this->params['nearby']) && count($data) < $pagesize) {
                    $page = 0;
                    $i = -1;
                } else {
          
                    //$gradeNoble = GradeNoble::where(['id' => ['gt', 0]])->cache(86400)->column('id, icon, circle');
                    $gradeNoble = GradeNoble::where(['id' => ['gt', 0]])->cache(30)->column('id, icon, circle');
                    // $ids = array_column($data, 'user_id');

                    // $user_labels = Labels::lists($ids);
    
                    // $car_ids = Db::name('user_car')->where(['user_id' => ['in', $ids], 'expire' => ['gt', time()], 'is_select' => 1])->column('user_id, car_id');
                    // if ($car_ids) {
                    //     $car_covers = Db::name('car')->where(['id' => ['in', $car_ids]])->cache(86400)->column('id, cover');
                    // } else {
                    //     $car_covers = [];
                    // }
                    $car_covers = [];
                    $photo_uids = [];
                    $photos = [];
                    // foreach ($data as $key => $item) {
                    //     if ($item['voice_auth'] != 2 || !$item['voice']|| !$item['voice_time']) {
                    //         $photo_uids[] = $item['user_id'];
                    //     }
                    // }
                    
                    // if ($photo_uids) {
                    //     $userImgs = UserImg::where(['types' => 1, 'user_id' => ['in', $photo_uids], 'burn' => 0, 'packet' => 0, 'is_auth' => 0, 'is_avatar' => 0, 'status' => 1])->order('id desc')->cache(7200)->select();
                    //     $photos = [];
                    //     foreach ($userImgs as $img) {
                    //         if (!isset($photos[$img['user_id']]) || count($photos[$img['user_id']]) < 4) {
                    //             $pic = json_decode($img['picthumb'], true);
                    //             if (isset($pic[0])) {
                    //                 $photos[$img['user_id']][] = changeUrl($pic[0]);
                    //             }
                    //         }
                    //     }
                    // }


        
                    $timenow = time();
                    foreach ($data as $key => $item) {
                         $data[$key]['city'] =$item['offten_city'];
                        //是否打过招呼  1是  0否
                        $is_say_hello = cache('greet'.$this->member['id'].'-to-' . $item['user_id']);
                        if ($is_say_hello){
                            $data[$key]['is_say_hello'] =1;
                        }else{
                            $data[$key]['is_say_hello'] =0;
                        }
                        if (!$this->params['video_mate'] && !$this->params['voice_mate'] && !$this->params['fate']) {
                            if (isset($car_ids[$item['user_id']]) && isset($car_covers[$car_ids[$item['user_id']]])) {
                                $data[$key]['car_cover'] = changeUrl($car_covers[$car_ids[$item['user_id']]]);
                            } else {
                                $data[$key]['car_cover'] = '';
                            }
                        }

                        $data[$key]['is_vip'] = $item['noble_grade'] && $item['noble_time'] > time() ? 1 : 0;
                        $data[$key]['is_new'] = (strtotime($item['register_datetime']) + 86400) > time() ? 1 : 0;

                        $data[$key]['user_distance'] = '';
                        if ($item['hide_distance']) {
                            $data[$key]['user_distance'] = '保密';
                        } else if ($item['latitude'] && $item['longitude']){
                            $distance = $item['xuni_discount'] + 0 ? $item['xuni_discount'] : $item['distance'];
                            $data[$key]['user_distance'] = $distance >= 1000 ? number_format(($distance / 1000), 1) . 'km' : number_format($distance, 1) . 'm';
                        }

                        if (!$this->params['nearby']) {
                            $data[$key]['user_distance'] = '';
                        }

                        $last_login_datetime = strtotime($item['last_login_datetime']);
                        // if ($item['is_online'] == 0) {
                        //     if ($timenow - 3*86400 < $last_login_datetime) {
                        //         $data[$key]['is_online'] = 1;
                        //     }
                        // }
                        if ($item['is_banned']) {
                            $data[$key]['is_online'] = 0;
                        }

                        if ($data[$key]['is_online']) {
                            $data[$key]['last_login_datetime'] = $timenow - $last_login_datetime < 1800 ? '在线' : (substr($data[$key]['user_id'], -1) + 1 + substr($timenow, -3, 1)).'分钟前在线';
                        } else {
                            $data[$key]['last_login_datetime'] = '';
                        }

                        if ($item['noble_grade'] && $item['noble_time'] > time()) {
                            $data[$key]['noble_icon'] = $gradeNoble[$item['noble_grade']] ? $gradeNoble[$item['noble_grade']]['icon'] : '';
                            $data[$key]['noble_circle'] = $gradeNoble[$item['noble_grade']] ? $gradeNoble[$item['noble_grade']]['circle'] : '';
                        } else {
                            $data[$key]['noble_icon'] = '';
                            $data[$key]['noble_circle'] = '';
                        }

                        $data[$key]['voice'] = '';
    
                        if ($item['voice_auth'] != 2 || !$item['voice']|| !$item['voice_time']) {
                            $data[$key]['photos'] = $photos[$item['user_id']] ?? [];
                        } else {
                            $data[$key]['photos'] = [];
                        }

                        $labels = $user_labels[$item['user_id']] ?? [];
                        $data[$key]['labels'] = array_slice($labels, 0, 5);


                        // $data[$key]['entertainment_text'] = Db::name('user_entertainment')->where(['role_type'=>$data[$key]['entertainment']])->value('name');
                         $data[$key]['entertainment_text'] = '娱乐';
                        // if ($data[$key]['entertainment_child']) {
                        //     $additionValue = 1;
                        //     $numbersArray = explode(',', $data[$key]['entertainment_child']);
                        //     $resultArray = array_map(function ($number) use ($additionValue) {
                        //         return $number + $additionValue;
                        //     }, $numbersArray);
                        //     $resultString = implode(',', $resultArray);

                        //     $data[$key]['entertainment_child_text'] = Db::name('user_entertainment')->where(['id'=>['in',$resultString]])->column('name');
                        //     $data[$key]['entertainment_child_text'] = implode('|',$data[$key]['entertainment_child_text']);
                        // }

                        $data[$key]['is_chat_discount'] = false;
                        // if (isset($chat_discount_users[$data[$key]['user_id']])) {
                        //     $data[$key]['is_chat_discount'] = (floatval($chat_discount_users[$data[$key]['user_id']]) / 10) . '折';
                        // }
                        
                        // $isHide = ConfigPersonal::where('user_id', $item['user_id'])->value('is_hide');
                        // $data[$key]['is_hide'] = is_null($isHide) ? 0 : $isHide;
                         $data[$key]['is_hide'] =  0 ;

                        unset($data[$key]['img_auth'], $data[$key]['xuni_discount'],$data[$key]['noble_grade'], $data[$key]['noble_time'],
                            $data[$key]['notlimit_city'], $data[$key]['distance'], $data[$key]['register_datetime'], $data[$key]['role'], $data[$key]['hide_online_time'], $data[$key]['voice_auth']);
                        unset($data[$key]['yqr'], $data[$key]['latitude'], $data[$key]['longitude']);
                    }
                }
            } else {
                $data = [];

                if ($page && ($this->params['hot'] || $this->params['nearby'])) {
                    $page = 0;
                    $i = -1;
                } else if ($page == 0 && $num == 1) {
                    $indexskip = 0;
                    $i = -1;
                } else {
                    if ($this->params['fate']) {
                        $fate_chat = 0;
                    }
                    if ($this->params['video_mate'] || $this->params['voice_mate']) {
                        Db::name('records_mate')->where(['user_id' => $this->member['id']])->delete();
                    }
                }
            }
        }

        // if ($this->member && $this->member['sex'] == '男') {
        //     action('api/Login/systemPushLianmaiMale');
        // }
        return $this->pass($data, 'result');
        // return $this->pass(base64_encode(json_encode($data, JSON_UNESCAPED_UNICODE)), 'result');
    }


    public function search()
    {
        $entertainment = $this->params['entertainment'] ?? 0;
        $page = $this->params['page'] ?? 0;
        $pagesize = $this->params['pagesize'] ?? 10;
        //$searchUserCacheKey = 'searchUser:'.$this->member['id'].':'.$this->params['name'].':'.$entertainment.':'.$page.':'.$pagesize;
        $searchUserCacheKey = 'searchUser:'.$this->params['name'].':'.$entertainment.':'.$page.':'.$pagesize;
        //cache($searchUserCacheKey, null);//清除缓存，防止缓存干扰
        $data = cache($searchUserCacheKey);

        $data='';
        if ($data && is_array($data)) {
            return $this->pass($data, 'result');
        }
        // var_dump($this->MIXparams);exit;
        $this->params['video_mate'] = $this->params['video_mate'] ?? '';
        $this->params['voice_mate'] = $this->params['voice_mate'] ?? '';

        $limit = Db::name('search_limit')->where(['user_id'=>$this->member['id']])->find();

        $where = "proxy = 0 and hide_search = 0 and sandbox = 0 and delete_time = 0 and reg = 1";

        if (!$entertainment) {
            //$where = "entertainment !=1 and proxy = 0 and hide_search = 0 and sandbox = 0 and delete_time = 0 and reg = 1 and age >= 18 and quality != 1";
            $where = "entertainment !=1 and proxy = 0 and hide_search = 0 and sandbox = 0 and delete_time = 0 and reg = 1 and age >= 18";
        }


        if($limit){
            if (!$entertainment) {
                return $this->pass([]);
            }
            $where .= ' and entertainment = 1';
        }


        $config = Config::where(['category' => ['in', ['kefu', 'user']]])->column('title, content');


        $where .= " and id <> " . $config['id'];


        if ($config['id'] == $this->member['id']) {
            $where = "delete_time = 0";
        } else if (!$entertainment) {
            // $sex = $this->member['sex'] == '男' ? '女' : '男';
            // $where .= " and sex = '$sex'";
        }

        if ($this->params['name']) {
            $where .= " and (name LIKE '%" . $this->params['name'] . "%' or id LIKE '%" . $this->params['name'] . "%')";
        }

        $distance_sql = distance($this->params['latitude'], $this->params['longitude']);
        $field = 'id user_id, name user_name, head_portrait user_head, sex user_sex, age user_age, city, occupation,
            img_auth, is_online, is_identity_authentication, last_login_datetime, nvshen, hide_online_time,
            noble_grade, noble_time, hide_distance, kejian, xuni_discount, notlimit_city, role, voice,
            voice_time, voice_auth, stature, realname_auth, register_datetime, yqr, auth_tag, entertainment, self_slogan, entertainment_child,is_banned,nation';
        //如果用户被禁言 则不允许展示
        $limit_chat = Db::name('limit_chat')->order('time desc')->column('user_id');
        $where .= " and id not in (" . implode(',', $limit_chat) . ") ";
        $sql = "select $field, $distance_sql from user where $where  group by user_id order by last_login_datetime desc limit " . ($page * $pagesize) . ", $pagesize";
        // var_dump($sql);exit;
        $data = Db::query($sql);

        if ($this->params['video_mate'] || $this->params['voice_mate']) {
            Db::name('records_mate')->insert(['user_id' => $this->member['id'], 'to_user' => $data[0]['user_id'], 'create_time' => time()]);
        }

        //$gradeNoble = GradeNoble::where(['id' => ['gt', 0]])->cache(86400)->column('id, icon, circle');
        $gradeNoble = GradeNoble::where(['id' => ['gt', 0]])->cache(30)->column('id, icon, circle');

        $ids = array_column($data, 'user_id');

        $user_labels = Labels::lists($ids);

        $car_ids = Db::name('user_car')->where(['user_id' => ['in', $ids], 'expire' => ['gt', time()], 'is_select' => 1])->column('user_id, car_id');
        if ($car_ids) {
            $car_covers = Db::name('car')->where(['id' => ['in', $car_ids]])->cache(86400)->column('id, cover');
        } else {
            $car_covers = [];
        }

        $photo_uids = [];
        $photos = [];
        foreach ($data as $key => $item) {
            if ($item['voice_auth'] != 2 || !$item['voice']|| !$item['voice_time']) {
                $photo_uids[] = $item['user_id'];
            }
        }
        
        if ($photo_uids) {
            $userImgs = UserImg::where(['types' => 1, 'user_id' => ['in', $photo_uids], 'burn' => 0, 'packet' => 0, 'is_auth' => 0, 'is_avatar' => 0, 'status' => 1])->order('id desc')->cache(7200)->select();
            $photos = [];
            foreach ($userImgs as $img) {
                if (!isset($photos[$img['user_id']]) || count($photos[$img['user_id']]) < 4) {
                    $pic = json_decode($img['picthumb'], true);
                    if (isset($pic[0])) {
                        $photos[$img['user_id']][] = changeUrl($pic[0]);
                    }
                }
            }
        }
        $chat_discount_users = Db::name('act_chat_discount_user')->where(['state'=>0, 'starttime'=>['<=', datetime()], 'endtime'=>['>=', datetime()]])->fetchSql(false)->column('discount','user_id');
        $timenow = time();
        foreach ($data as $key => $item) {

            $data[$key]['is_vip'] = $item['noble_grade'] && $item['noble_time'] > time() ? 1 : 0;
            $data[$key]['is_new'] = (strtotime($item['register_datetime']) + 86400) > time() ? 1 : 0;

            if ($item['hide_distance']) {
                $data[$key]['user_distance'] = '保密';
            } else {
                $distance = $item['xuni_discount'] + 0 ? $item['xuni_discount'] : $item['distance'];
                $data[$key]['user_distance'] = $distance >= 1000 ? number_format(($distance / 1000), 1) . 'km' : number_format($distance, 1) . 'm';
            }

            $last_login_datetime = strtotime($item['last_login_datetime']);
            // if ($item['is_online'] == 0) {
            //     if ($timenow - 3*86400 < $last_login_datetime) {
            //         $data[$key]['is_online'] = 1;
            //     }
            // }

            if ($item['is_banned']) {
                $data[$key]['is_online'] = 0;
            }

            if ($data[$key]['is_online']) {
                // $data[$key]['last_login_datetime'] = changeTime($data[$key]);
                $data[$key]['last_login_datetime'] = $timenow - $last_login_datetime < 1800 ? '在线' : (substr($data[$key]['user_id'], -1) + 1 + substr($timenow, -3, 1)).'分钟前在线';
            } else {
                $data[$key]['last_login_datetime'] = '';
            }

            if ($item['noble_grade'] && $item['noble_time'] > time()) {
                $data[$key]['noble_icon'] = $gradeNoble[$item['noble_grade']] ? $gradeNoble[$item['noble_grade']]['icon'] : '';
                $data[$key]['noble_circle'] = $gradeNoble[$item['noble_grade']] ? $gradeNoble[$item['noble_grade']]['circle'] : '';
            } else {
                $data[$key]['noble_icon'] = '';
                $data[$key]['noble_circle'] = '';
            }

            if ($item['voice_auth'] != 2) {
                $data[$key]['voice'] = '';
            }

            if ($item['voice_auth'] != 2 || !$item['voice']|| !$item['voice_time']) {
                $data[$key]['photos'] = $photos[$item['user_id']] ?? [];
            } else {
                $data[$key]['photos'] = [];
            }


            $data[$key]['entertainment_text'] = Db::name('user_entertainment')->where(['role_type'=>$data[$key]['entertainment']])->value('name');
            if ($data[$key]['entertainment_child']) {
                $additionValue = 1;
                $numbersArray = explode(',', $data[$key]['entertainment_child']);
                $resultArray = array_map(function ($number) use ($additionValue) {
                    return $number + $additionValue;
                }, $numbersArray);
                $resultString = implode(',', $resultArray);

                $data[$key]['entertainment_child_text'] = Db::name('user_entertainment')->where(['id'=>['in',$resultString]])->column('name');
                $data[$key]['entertainment_child_text'] = implode('|',$data[$key]['entertainment_child_text']);
            }

            $labels = $user_labels[$item['user_id']] ?? [];
            $data[$key]['labels'] = array_slice($labels, 0, 5);
                
            $data[$key]['is_chat_discount'] = false;
            if (isset($chat_discount_users[$data[$key]['user_id']])) {
                $data[$key]['is_chat_discount'] = (floatval($chat_discount_users[$data[$key]['user_id']]) / 10) . '折';
            }
            
            $isHide = ConfigPersonal::where('user_id', $item['user_id'])->value('is_hide');
            $data[$key]['is_hide'] = is_null($isHide) ? 0 : $isHide;

            unset($data[$key]['img_auth'], $data[$key]['xuni_discount'],$data[$key]['noble_grade'], $data[$key]['noble_time'],
                $data[$key]['notlimit_city'], $data[$key]['distance'], $data[$key]['register_datetime'], $data[$key]['role'],
                $data[$key]['hide_online_time'], $data[$key]['voice_auth']);

            unset($data[$key]['user_distance']);
            unset($data[$key]['yqr']);
        }
        
        if (sizeof($data)) {
            $AA = cache($searchUserCacheKey, $data, 3600);
            file_put_contents('./log.txt', json_encode($AA), FILE_APPEND);
        }

        return $this->pass($data, 'result');
    }



    public function info()
    {
        // var_dump($this->params);exit;
        $id = $this->params['to_user'] ?? $this->member['id'];
        $user_id = $this->params['user_id'] ?? $this->member['id'];
        $hunjie = $this->params['hunjie'] ?? 0;
        // $user_id = $this->params['user_id'] ?? 12;

        if (!$this->member || $this->member['reg']==0) {
            return $this->miss('请登录',402);
        }

        $distance_sql = distance($this->params['latitude']??0, $this->params['longitude']??0);

        $table = 'user';
        // if ($user_id > 30000000) {
        //     $database9 = getenv('DB9_DATABASE');
        //     $table = $database9 . '.user';
        // }

        $field = 'id, name, head_100, head_300, head_portrait, sex, phone, age,offten_city city, offten_city, occupation, slogan, level, self_slogan, 
                constellation, img_auth, is_online, is_identity_authentication, hide_online_time, nvshen, last_login_datetime, 
                hide_distance, kejian, xuni_discount, notlimit_city, role, img_auth, photo_price, stature, 
                weight, wxcount, qq, lianmai_limit, paypwd, shoushi, hide_search, volley, zhifucount, zhifuname, proxy, 
                invite_count, vip_num, vip_count, shouyi, dy_program, dy_conditions, yqm send_code, 
                score, tycoon, charm_value, zan, angel, video, cover, voice, voice_auth, voice_zan, noble_grade, noble_time, 
                attention, following, friend, birthday, monthly_salary, education_background, emotion, realname_auth, register_datetime, 
                line_price,heart, zhaohu_time, school_of_graduation, live_status, is_house_purchase, is_car_purchase, tags, speaker, 
                through_membership, self_images, voice_time, free_chat, free_voice, free_video, yqr, is_banned, banned_end_time, banned_desc, wechat, wechat_name, reg, entertainment, auth_tag, income_auth, marry_auth, is_education_authentication, house_auth, car_auth,entertainment_child,nation,premarital,premarital,to_like,bank,bank_number,bank_user_name,beans';

        $sql = "select $field, $distance_sql from $table where id = $user_id and delete_time = 0";

        $data = Db::query($sql);
        // var_dump($data);exit;
        $timenow = time();
        if ($data) {
            $data = $data[0];
            
            $isHide = ConfigPersonal::where('user_id', $data['id'])->value('is_hide');
            $data['is_hide'] = is_null($isHide) ? 0 : $isHide;

            if ($hunjie) {
                $userProfile = Db::name('user_profile')->where(['user_id'=>$data['id']])->field('id,create_time,update_time','filter')->find();
                if ($userProfile) {
                    $userProfile['pull_line'] = strtotime($userProfile['pull_line']) < time() ? '' : $userProfile['pull_line'];
                    $userProfile['matchmaker_info'] = Db::name('user_profile')->where(['user_id'=>$userProfile['matchmaker_id']])->field('id,name,head_portrait')->find();
                    $data = array_merge($data, $userProfile);
                }
            }
    
            if (!$id && (strtotime($data['last_login_datetime']) + 86400 * 3) < time()) {
                UserModel::update(['id' => $user_id, 'is_online' => 0]);
                return $this->return['user.error.afreshLogin'];
            }

            $config = Config::where(['category' => ['in', ['user', 'kefu', 'defend', 'invite', 'family', 'sayhi', 'two_way_charge']]])->cache(3600)->column('title, content');

            $kefu = intval($config['id']);
    
            $data['configPersonal'] = $configPersonal = Db::name('config_personal')->where(['user_id' => $user_id])->find();
            if (!$configPersonal) {
                $data['configPersonal'] = $configPersonal = ConfigPersonal::createData($user_id, $data['sex'], true);
            }

            if ($data['configPersonal']) {
                if ($data['configPersonal']['chat_price'] && $data['configPersonal']['chat_price'] > 2) {
                    $data['configPersonal']['chat_price'] = 2;
                }
                if ($data['configPersonal']['voice_price'] && $data['configPersonal']['voice_price'] > 15) {
                    $data['configPersonal']['voice_price'] = 15;
                }
                if ($data['configPersonal']['video_price'] && $data['configPersonal']['video_price'] > 30) {
                    $data['configPersonal']['video_price'] = 30;
                }
            }


            $data['zhaohu'] = 0;
            if ($user_id != $kefu && ($data['zhaohu_time'] + $config['sayhi_times']) < time() && !$id) {
                if (isset($configPersonal['fate_switch']) && ($configPersonal['fate_switch'] + 0)) {
                    $data['zhaohu'] = 1;
                }
            }

            $data['tycoon'] = round($data['tycoon']);
            $data['dy_program'] = explode(',', $data['dy_program']);
            $data['dy_conditions'] = explode(',', $data['dy_conditions']);
            $data['is_vip'] = ($data['noble_grade'] && $data['noble_time'] > time()) ? 1 : 0;
            if ($data['is_online']) {
                // $data['last_login_datetime'] = changeTime($data);
                $data['last_login_datetime'] = $timenow - strtotime($data['last_login_datetime']) < 1800 ? '在线' : (substr($data['id'], -1) + 1 + substr($timenow, -3, 1)).'分钟前在线';
            } else {
                $data['last_login_datetime'] = '';
            }
            $data['self_images'] = $data['self_images'] ? explode(',', $data['self_images']) : [];

            // $data['voice'] = '';

            $data['set_paypwd'] = $data['paypwd'] ? 1 : 0;
            $data['register_date'] = date('Y年m月d日', strtotime($data['register_datetime']));
            $data['register_days'] = round((time() - strtotime($data['register_datetime'])) / 3600 / 24);

            $data['photo_show'] = UserImg::where(['user_id' => $user_id, 'is_auth' => 0, 'status' => 1])->order('id desc')->limit(10)->cache('photos' . $user_id)->column('pic');
            foreach ($data['photo_show'] as $key => $item) {
                $data['photo_show'][$key] = json_decode($item, true)[0];
            }

            if ($user_id > 30000000) {
                $data['head_portrait'] = _ossUrl(1) . $data['head_portrait'];
            }

            if ($data['photo_show']) {
                if ($data['photo_show'][0] != $data['head_portrait']) {
                    array_unshift($data['photo_show'], $data['head_portrait']);
                }
            } else {
                $data['photo_show'] = [$data['head_portrait']];
            }

            $data['photo_count'] = (new UserImg)->where(['user_id' => $user_id, 'is_auth' => 0, 'status' => 1])->cache('photosCount' . $user_id)->count();

            $data['state'] = 0;

            $data['burn'] = 0;


            // if (1==1) {//显示土豪、魅力图标等
            //     // 土豪
            //     //$gradeTycoon = Db::name('grade_tycoon')->where(['min' => ['elt', $data['tycoon']]])->order('grade desc')->cache(true)->find();
            //     // $gradeTycoon = Db::name('grade_tycoon')->where(['min' => ['elt', $data['tycoon']]])->order('grade desc')->find();
            //     // $data['tycoonGrade'] = $gradeTycoon['grade'];
            //     // $data['tycoonName'] = $gradeTycoon['name'];
            //     // $data['tycoonIcon'] = $gradeTycoon['icon'];

            //     // 魅力
            //     //$gradeCharm = Db::name('grade_charm')->where(['min' => ['elt', $data['charm_value']]])->order('grade desc')->cache(true)->find();
            //     $gradeCharm = Db::name('grade_charm')->where(['min' => ['elt', $data['charm_value']]])->order('grade desc')->find();
            //     $data['charmGrade'] = $gradeCharm['grade'];
            //     $data['charmName'] = $gradeCharm['name'];
            //     $data['charmIcon'] = $gradeCharm['icon'];
            // }

            // if (false) {
            //     $data['gift'] = Db::name('gift_record t1')
            //         ->join('gift t2', 't2.id = t1.gift_id')
            //         ->where(['t1.to_user' => $user_id])
            //         ->order('t1.id desc')
            //         ->field('t1.id, t1.gift_id, sum(t1.num) num, t2.name, t2.price, t2.preview, t2.cover')
            //         ->group('t1.gift_id')
            //         ->cache(1800)
            //         ->select();
            // }

            $data['grade_charm'] = GradeCharm::where(['min' => ['elt', $data['charm_value']]])->order('grade desc')->find();
            // if (false) {

            //     $angel = UserDefend::get(['to_user' => $user_id, 'angel' => 1]);

            //     // 守护天使
            //     if (!$data['angel'] || !$angel) {
            //         if (!isset($data['charmGrade'])) {
            //             $gradeCharm = GradeCharm::where(['min' => ['elt', $data['charm_value']]])->order('grade desc')->find();
            //         }

            //         if ($data['sex'] == '女') {
            //             $angel_min = $gradeCharm['grade'] * $config['female_times'];

            //             if ($angel_min < $config['female_min']) {
            //                 $angel_min = $config['female_min'];
            //             }
            //         } else {
            //             $angel_min = $gradeCharm['grade'] * $config['male_times'];

            //             if ($angel_min < $config['male_min']) {
            //                 $angel_min = $config['male_min'];
            //             }
            //         }

            //         $userDefend = UserDefend::get(['user_id' => $id, 'to_user' => $user_id]);

            //         $data['angel_min'] = $userDefend ? $angel_min - $userDefend->money : $angel_min;
            //     } else {
            //         $angel_min = $angel->money;

            //         if ($data['sex'] == '女') {
            //             if ($angel->money < $config['female_min']) {
            //                 $angel_min = $config['female_min'];
            //             }
            //         } else {
            //             if ($angel->money < $config['male_min']) {
            //                 $angel_min = $config['male_min'];
            //             }
            //         }

            //         $userDefend = UserDefend::get(['user_id' => $id, 'to_user' => $user_id]);

            //         $data['angel_min'] = $userDefend ? $angel_min - $userDefend->money : $angel_min;

            //         $data['angel_avatar'] = UserModel::where(['id' => $angel['user_id']])->value('head_100');

            //         $gradeDefend = GradeDefend::where(['min' => ['elt', $angel['money']]])->order('grade desc')->find();

            //         $data['angel_name'] = $gradeDefend['name'];
            //         $data['angel_grade'] = $gradeDefend['grade'];
            //         $data['angel_icon'] = $gradeDefend['icon'];
            //     }

            //     $data['angel_min'] = $data['angel_min'] ?: 1;
            // }

            // if (false) {
            //     $data['defends_count'] = Db::name('user_defend')->where(['to_user' => $user_id])->count();
            //     $data['defends'] = Db::name('user_defend t1')
            //         ->field('t1.id, t1.user_id userid, t1.angel, t1.money, t1.update_time, t2.name,t2.head_100')
            //         ->join('user t2', 't2.id = t1.user_id')
            //         ->where(['t1.to_user' => $user_id])
            //         ->order('t1.money desc')->limit(3)->select();

            //     foreach ($data['defends'] as $key => $item) {
            //         $data['defends'][$key]['intimate'] = sprintf("%.1f", $item['money'] * 0.1);
            //         $data['defends'][$key]['days'] = ceil((time() - $item['update_time']) / 86400);

            //         unset($data['defends'][$key]['money'], $data['defends'][$key]['money']);
            //     }
            // }

            $other = false;
            if ($id && $user_id != $id) {
                $other = true;
                $data['volley'] = changefloor($data['volley'] * 0.9);

                $blacklist = Blacklist::where(['user_id' => $user_id, 'to_user' => $id])->cache('black' . $user_id . '_' . $id)->find();
                $data['pull_black'] = $blacklist ? 1 : 0;

                $attention = Attention::where(['user_id' => $id, 'to_user' => $user_id, 'sys_channel' => 1])->cache('follow' . $id . '_' . $user_id)->find();
                $data['love'] = $attention ? 1 : 0;


                // 聊天打折
                $overpayscale = 0;
                // 获取所有关联账号的总支付
                // $overpayscale = UserIntimateService::Count($id, $user_id, true);
                // if ($overpayscale) {
                //     $chat_scale['scale'] = $overpayscale;
                // } else {
                //     $chat_scale = Db::name('limit_chat_price')->where($id>$user_id ? 'user_id='.$user_id. ' and another_id='. $id : 'user_id='.$id. ' and another_id='. $user_id)->find();
                // }

                // if ($chat_scale) {
                //     $data['configPersonal']['chat_price'] = isset($data['configPersonal']['chat_price']) ? round($data['configPersonal']['chat_price'] * $chat_scale['scale'] / 100, 2) : 0;
                //     $data['configPersonal']['voice_price'] = isset($data['configPersonal']['voice_price']) ? round($data['configPersonal']['voice_price'] * $chat_scale['scale'] / 100, 2) : 0;
                //     $data['configPersonal']['video_price'] = isset($data['configPersonal']['video_price']) ? round($data['configPersonal']['video_price'] * $chat_scale['scale'] / 100, 2) : 0;
                // }

                
                $seeRecord = SeeRecord::get(['user_id' => $user_id, 'the_user' => $id]);
                if ($seeRecord) {
                    SeeRecord::update(['id' => $seeRecord->id, 'addtime' => date("Y-m-d H:i:s")]);
                } else {
                    SeeRecord::create(['user_id' => $user_id, 'the_user' => $id]);
                }
    
                $data['wxcount'] = $data['qq'] = 0;
                

                $data['pingjia'] = 0;

                $couple = $id < $user_id ? $id . ',' . $user_id : $user_id . ',' . $id;
                $userIntimate = UserIntimate::get(['couple_a' => $couple]);
                $data['intimate'] = $userIntimate ? $userIntimate['intimate'] : 0;

                $configPersonal = ConfigPersonal::get(['user_id' => $id]);

                if (!$configPersonal || !$configPersonal['hide_visit']) {
                    UserModel::where(['id' => $user_id])->setInc('see');
                }
                $mine = Db::name('user')->find($id);


                $ChatChargeRecordsMap = [
                    'user_id' => $user_id,
                    'another_id' => $id,
                ];
                $ChatChargeRecordsField = 'user_remark';
                if ($id < $user_id) {
                    $ChatChargeRecordsMap = [
                        'user_id' => $id,
                        'another_id' => $user_id,
                    ];
                    $ChatChargeRecordsField = 'another_remark';
                }

                $remarkname = Db::name('chat_charge_records')->where($ChatChargeRecordsMap)->value($ChatChargeRecordsField);
                $data['remarkname'] = $remarkname ?? '';

                $data['in_blacklist'] = Db::name('blacklist')->where(['user_id'=>$id, 'to_user'=>$user_id])->count();
                $data['hide_chat'] = $user_id > 30000000;

                $data['institutional'] = Db::name('user_attestation')->where(['user_id'=>$user_id, 'status'=>1, 'types'=>4])->value('hospital');

                if ($data['configPersonal']['hide_experience']) {
                    $data['experience'] = [];
                } else {
                    $experience = Db::name('user_attestation')->where(['types'=>2,'user_id'=>$user_id, 'status'=>1])->column('category');
                    $experience = implode(',',$experience);
                    $data['experience'] = Db::name('topic')->where(['id'=>['in',$experience]])->column('name');
                }

                if ($data['configPersonal']['hide_expertise']) {
                    $data['expertise'] = [];
                } else {
                    $expertise = Db::name('user_attestation')->where(['types'=>1,'user_id'=>$user_id, 'status'=>1])->column('category');
                    $expertise = implode(',',$expertise);
                    $data['expertise'] = Db::name('topic')->where(['id'=>['in',$expertise]])->column('name');
                }

                $data['real_age'] = 0;
                if ($data['realname_auth'] == 2) {
                    $user_certification = Db::name('user_certification')->where(['user_id'=>$data['id']])->value('data');
                    if ($user_certification) {
                        $realbirthDay = _getDateFromIdcard($user_certification);
                        $realAge = countage($realbirthDay);
                        $setAge = $data['age'];
                        if ($setAge <= $realAge + 5 || $realAge - 5 <= $setAge) {
                            $data['real_age'] = $setAge;
                        }
                    }
                }



                $data['payer_id'] = $this->member['sex']=='男'?$this->member['id']:$data['id'];
                $configTwoWayCharge = Config::index('two_way_charge');
                if ($configTwoWayCharge['two_way_charge_status'] == 1 && ((strtotime($this->member['register_datetime']) > strtotime($configTwoWayCharge['two_way_charge_reg_time'])) || (strtotime($data['register_datetime']) > strtotime($configTwoWayCharge['two_way_charge_reg_time'])))) {
                    $ChatChargeRecordMap = $this->member['id'] < $data['id'] ? [
                        'user_id' => $this->member['id'],
                        'another_id' => $data['id'],
                    ] :  [
                        'user_id' => $data['id'],
                        'another_id' => $this->member['id'],
                    ];
                    $ChatChargeRecords = Db::name('chat_charge_records')->master(true)->where($ChatChargeRecordMap)->find();
                    if ($ChatChargeRecords && $ChatChargeRecords['payer']) {
                        $data['payer_id'] = $data['id'] == $ChatChargeRecords['payer'] ? $data['id'] : $this->member['id'];
                    }
                }

                $chat_discount = Db::name('act_chat_discount_user')->where(['user_id'=>$data['id'],'state'=>0, 'starttime'=>['<=', datetime()], 'endtime'=>['>=', datetime()]])->fetchSql(false)->find();
                $data['is_chat_discount'] = false;
                if ($chat_discount) {
                    $data['is_chat_discount'] = (floatval($chat_discount['discount']) / 10) . '折';
                    if ($data['configPersonal']) {
                        $data['configPersonal']['chat_price'] = number_format($data['configPersonal']['chat_price'] * $chat_discount['discount'] / 100, 2);
                        $data['configPersonal']['voice_price'] = number_format($data['configPersonal']['voice_price'] * $chat_discount['discount'] / 100, 2);
                        $data['configPersonal']['video_price'] = number_format($data['configPersonal']['video_price'] * $chat_discount['discount'] / 100, 2);
                    }
                }
                $exp_topic = Db::name('user_attestation')->where(['user_id'=>$user_id, 'status'=>1, 'types'=>6])->column('category');

                $data['apply_un_blacklist'] = Db::name('apply_un_blacklist')->where(['touser_id'=>$user_id, 'user_id'=>$id, 'state'=>['in', [0,-1]]])->find();
                $data['apply_un_blacklist'] = $data['apply_un_blacklist']?$data['apply_un_blacklist']:false;

                unset($data['zhifucount'], $data['zhifuname'], $data['wechat'], $data['wechat_name'], $data['phone']);
            } else 
            {
                // action('api/privatechat/all_read');
                $task_contain = ['avatar', 'voice', 'info', 'more_info', 'perfect_info', 'real_avatar'];
                $taskWhere = ['name' => ['in', $task_contain]];
                $taskWhere['sex_limit'] = $data['sex'] == '女' ? ['in', [0, 1]] : ['in', [0, 2]];
                $tasks = Db::name('task')->where($taskWhere)->cache('task')->column('name, title, reward, reward_type');
                $userTask = Db::name('user_task')->where(['task' => ['in', $task_contain], 'user_id' => $user_id])->cache('userTask' . $user_id)->column('task');

                $task = [];
                foreach ($task_contain as $item) {
                    if (isset($tasks[$item]) && ($tasks[$item]['reward'] + 0) && !in_array($item, $userTask)) {
                        $task[$item] = ['title' => $tasks[$item]['title'], 'reward' => $tasks[$item]['reward'], 'reward_type' => $tasks[$item]['reward_type']];
                    }
                }

                $data['task'] = $task;

                
                $data['frozen_score'] = Db::name('wallet_frozen')->where(['user_id'=>$user_id])->value('value');
                $data['frozen_score'] = $data['frozen_score'] ?? 0;
                
                $data['limit_age_change'] = Db::name('change_age_limit')->where(['user_id'=>$user_id])->find();
                $data['limit_age_change'] = $data['limit_age_change'] ? 1 : 0;

                $data['charging_settings'] = 1;
                $data['changeHeadInfo'] = Db::name('user_material_verify')->where(['types'=>1,'user_id'=>$user_id,'status'=>0])->field('content,status')->order('id desc')->find();

                $data['banned_tip'] = $data['is_banned'];

                $is_experience = Db::name('user_attestation')->where(['types'=>2,'user_id'=>$user_id, 'status'=>1])->column('category');
                $data['is_experience'] = sizeof($is_experience) ? 1 : 0;
                $data['experience_count'] = sizeof(array_filter(explode(',',implode(',',$is_experience))));

                $data['email_account'] = Db::name('user_auth')->where(['user_id'=>$this->member['id'], 'type'=>1, 'state'=>1])->value('account');
                $data['email_account'] = $data['email_account'] ?: '';

                if ($data['is_banned'] && strtotime($data['banned_end_time']) > time() && $data['banned_desc']) {
                    $data['banned_end_time'] = $data['banned_end_time'] . ' 原因: '.$data['banned_desc'];
                }
                $data['is_banned'] = 0;
            
                $exp_topic = Db::name('user_attestation')->where(['user_id'=>$user_id, 'status'=>['in', [0,1]], 'types'=>6])->column('category');

                $hide_dating = Db::name('limit_dating')->where(['user_id'=>$user_id])->find();
                $data['hide_dating'] = $hide_dating ? 1 : 0;

                $data['visit_add_count'] = db('see_record')->where(['user_id' => $user_id, 'is_read' => 0])->count();
                $data['visit_count'] = db('see_record')->where(['user_id' => $user_id])->count();
                $intimates = Db::query("(SELECT * from user_intimate where couple_a like '$user_id,%' and intimate >= 2 and unshow = 0) union (SELECT * from user_intimate where couple_b like '$user_id,%' and intimate >= 2 and unshow = 0)");
                $mids = [];
                if ($intimates) {
                    foreach ($intimates as $item) {
                        $couple = explode(',', $item['couple_a']);
                        if ($couple[0] != $user_id && !in_array($couple[0], $mids)) {
                            $mids[] = $couple[0];
                            $contain[$couple[0]] = $item['intimate'];
                        }
                        if ($couple[1] != $user_id && !in_array($couple[1], $mids)) {
                            $mids[] = $couple[1];
                            $contain[$couple[1]] = $item['intimate'];
                        }
                    }
                }
                $mids = array_unique($mids);
                $data['m_friend'] = sizeof($mids);
                if ($this->member['sex'] == '女') {
                    $data['volley'] = $data['beans'];
                }

                // $friends = Db::query("(SELECT couple_a,unshow from user_intimate where couple_a like '$id,%' and intimate >= 2 and unshow in (0,2)) union (SELECT couple_a,unshow from user_intimate where couple_b like '$id,%' and intimate >= 2 and unshow in (0,1))");
                // $unRecycleUids = Db::name('user')->where([
                //     'id'=>['in',array_diff(explode(',',implode(',', array_column($friends,'couple_a'))), [$id])],
                //     'delete_time'=>0
                // ])->column('id');
                // $data['friends'] = sizeof($unRecycleUids);

                // $attention_ids_1 = Db::name('attention')->where(['user_id' => $user_id])->column('to_user');
                // $attention_ids_2 = Db::name('attention')->where(['to_user' => $user_id])->column('user_id');

                // foreach ($friends as $key => $value) {
                //     $uid = implode('', array_diff(explode(',', $value['couple_a']), [$id]));
                //     if (!in_array($uid, $unRecycleUids)) {
                //         continue;
                //     }
                //     if ($value['unshow'] == 3) continue;

                //     $unshow = 0;
                //     if ($value['unshow']) {
                //         if (stripos($value['couple_a'], $uid) > 0) {
                //             $unshow = $value['unshow'] == 1 ? $id : $uid;
                //         } else {
                //             $unshow = $value['unshow'] == 1 ? $uid : $id;
                //         }
                //     }

                //     if (!in_array($uid, $attention_ids_1) && $unshow != $user_id) {
                //         Db::name('attention')->insert(['user_id'=>$user_id, 'to_user'=>$uid]);
                //     }
                //     if (!in_array($uid, $attention_ids_2) && $unshow != $uid) {
                //         Db::name('attention')->insert(['user_id'=>$uid, 'to_user'=>$user_id]);
                //     }
                // }

            }


            $data['exp_topic'] = [];
            if (sizeof($exp_topic)) {
                $data['exp_topic'] = Db::name('topic')->where(['id'=>['in',implode(',',$exp_topic)]])->column('name');
            }

            $following_ids = Db::name('attention')->master()->where(['user_id' => $user_id, 'sys_channel' => 1])->column('to_user');
            $attention_ids = Db::name('attention')->master()->where(['to_user' => $user_id, 'sys_channel' => 1])->count();
            $friend_ids = Db::name('attention')->master()->where(['user_id' => ['in', $following_ids], 'to_user' => $user_id, 'sys_channel' => 1])->column('user_id');
            $ups = [];
            if ($data['following'] != sizeof($following_ids)) {
                Db::name('user')->where(['id'=>$user_id])->update(['following'=>sizeof($following_ids)]);
                $data['following'] = $ups['following'] = sizeof($following_ids);
            }
            if ($data['attention'] != $attention_ids) {
                $data['attention'] = $ups['attention'] = $attention_ids;
            }
            if ($data['friend'] != sizeof($friend_ids)) {
                $data['friend'] = $ups['friend'] = sizeof($friend_ids);
            }
            if (sizeof($ups)) {
                Db::name('user')->where(['id'=>$user_id])->update($ups);
            }

            $data['dy_count'] = Db::name('dymanic')
                            ->where(['shenhe'=>$other?1:['>=',-1], 'userid'=>$user_id, 'state'=>0])
                            ->count();
            $data['dy_count'] = $data['dy_count'] ? $data['dy_count'] : '0';
            $data['ser_count'] = Db::name('user_service')
                            ->where(['user_id'=>$user_id,'state'=>$other?1:['>=',-1], 'delete_time'=>0])
                            ->count();
            $data['mix_count'] = Db::name('dymanic_collection')
                            ->where(['user_id'=>$user_id,'state'=>$other?1:['>=',-1],'count'=>['>=',$other?1:0]])
                            ->count();

                // $data['stature'] = '';
                // $data['weight'] = '';
                // $data['city'] = '';
                // $data['occupation'] = '';
                $data['school_of_graduation'] = '';
                // $data['through_membership'] = '';
                // $data['live_status'] = '';
            $data['volley'] = intval($data['volley']);

            if (intval($config['family_switch'])) {
                $cluster = Cluster::get(['types' => 1, 'user_id' => $user_id, 'status' => 1]);

                if ($cluster) {
                    $data['cluster'] = [
                        'id' => $cluster['id'],
                        'name' => $cluster['name'],
                        'logo' => changeUrl($cluster['logo']),
                        'count' => $cluster['count'],
                        'ranking' => $cluster['ranking'],
                    ];
                } else {
                    $data['cluster'] = [];
                }
            } else {
                $data['cluster'] = [];
            }


            if ($data['noble_time'] > time() && $data['noble_grade']) {
                $data['is_noble'] = 1;

                //$gradeNoble = GradeNoble::where(['grade' => $data['noble_grade']])->cache(86400)->find();
                $gradeNoble = GradeNoble::where(['grade' => $data['noble_grade']])->cache(30)->find();
                if ($gradeNoble) {
                    $data['noble'] = [
                        'id' => $gradeNoble['id'],
                        'name' => $gradeNoble['name'],
                        'grade' => $gradeNoble['grade'],
                        'icon' => $gradeNoble['icon'],
                        'circle' => $gradeNoble['circle'],
                    ];
                } else {
                    $data['noble'] = [];
                }

                $data['noble_time'] = date('Y-m-d H:i:s', $data['noble_time']);
            } else {
                $data['is_noble'] = 0;
            }

            $userZan = UserZan::where(['types' => 2, 'user_id' => $id, 'to_user' => $user_id])->cache('zan' . $id . '_' . $user_id)->find();

            $data['had_voice_zan'] = $userZan ? 1 : 0;

            $data['tags'] = [];
            unset($data['xuni_discount'], $data['notlimit_city'], $data['user_distance'], $data['paypwd']);

            $data['count_zan'] = 0;
            $data['count_exp'] = 0;
            $data['count_col'] = 0;
            $dys = Db::name('dymanic')->where(['userid'=>$user_id])->field('thumbsup,xuni_thumbsup,lover')->select();
            $data['count_zan'] = array_sum(array_column($dys, 'thumbsup')) + array_sum(array_column($dys, 'xuni_thumbsup'));
            $data['count_exp'] = array_sum(array_column($dys, 'lover'));
            $data['count_col'] = $data['following'];


            if ($data['reg']==1) {
                $privacy = Db::name('user')->where(['reg'=>2, 'authcode'=>$data['id']])->field('id,name,head_portrait')->find();
                if ($privacy) {
                    $data['privacy_account'] = $privacy;
                }
            }

            $data['entertainment_text'] = Db::name('user_entertainment')->where(['role_type'=>$data['entertainment']])->value('name');
            if ($data['entertainment_child']) {

                $additionValue = 1;
                $numbersArray = explode(',', $data['entertainment_child']);
                $resultArray = array_map(function ($number) use ($additionValue) {
                    return $number + $additionValue;
                }, $numbersArray);
                $resultString = implode(',', $resultArray);

                $data['entertainment_child_text'] = Db::name('user_entertainment')->where(['id'=>['in',$resultString]])->column('name');
                $data['entertainment_child_text'] = implode('|',$data['entertainment_child_text']);
            }
        }

        if ($user_id == $this->member['id']) {
            UserModel::pushchatUnFirst($this->member);
        }
        
        
        //新增今日收益
        //$user_id = 20375658;
        $startTime = strtotime('today');
        $endTime = strtotime('+1 day');
        $data['today_profit'] = Db::name('yaoqing_records')
            ->where('uid',$user_id)
            ->where('time', '>=', $startTime)
            ->where('time', '<', $endTime)
            ->where('data',0)
            ->sum('money');
        
        
        return $this->pass($data, 'result');
    }

    public function removeFriend()
    {
        $touserids = $this->params['touserids'] ?? '';
        $touserids = explode(',',$touserids);
        if (sizeof($touserids) == 0) {
            return $this->miss('操作失败');
        }
        $num = 0;
        $last_id = Db::name('privatechat')->order('id desc')->value('id');
        $time = time();
        foreach ($touserids as $key => $touserid) {
            $timenow = time();
            if ($timenow - 10 > $time) continue;
            $str = $this->member['id'] . ',' . $touserid;
            $couple = $this->member['id'] > $touserid ? 'b' : 'a';

            $intimate = Db::name('user_intimate')->where(['couple_'. $couple => $str])->find();
            if (!$intimate) continue;

            if ($intimate['unshow'] == 3) continue;
            $state = $couple == 'a' ? 1 : 2;
            if ($intimate['unshow'] == $state) continue;

            if ($couple == 'a') {
                if ($intimate['unshow'] == 2) {
                    $state = 3;
                }
            } else {
                if ($intimate['unshow'] == 1) {
                    $state = 3;
                }
            }
            Db::name('user_intimate')->where(['id'=>$intimate['id']])->update(['unshow'=>$state]);
            $key = $this->member['id'] < $touserid ? 'another' : 'user';
            $where = [$key.'_id'=>$touserid, ($key=='user'?'another':'user').'_id'=>$this->member['id']];
            Db::name('chat_lists')->where($where)->delete();
            Db::name('chat_charge_records')->where($where)->delete();
            $db = Db::name('privatechat_dele_task')->insert(['userid'=>$this->member['id'], 'touserid'=>$touserid, 'last_id'=>$last_id,  'create_time'=>$timenow]);
            $db = Db::name('privatechat_dele_task')->insert(['userid'=>$touserid, 'touserid'=>$this->member['id'], 'last_id'=>$last_id,  'create_time'=>$timenow]);
            PrivatechatDeleTask::pushtask($this->member['id']);
            PrivatechatDeleTask::pushtask($touserid);

            Db::name('privatechat')->where("(userid=".$this->member['id']." and touserid=".$touserid.") or (userid=".$touserid." and touserid=".$this->member['id'].")")->update(['status'=>4]);
            Db::name('delete_liaoyou_records')->insert(['user_id'=>$this->member['id'], 'touser_id'=>$touserid, 'time'=>$timenow]);

            $num++;
        }
        return $num ? $this->pass('移除成功') : $this->miss('请稍后再试');
    }

    public function roles()
    {
         return $this->pass([]);
        $this->params['timestamp'] = $this->params['timestamp'] ?? 0;
        $data = Db::name('user_entertainment')->field('id,name,parent_id')->order('sort desc, id asc')->select();
        foreach ($data as &$value) {
            $value['id']--;
            $value['parent_id']--;
        }
        $data = _toTree($data, -1, 'parent_id');
        return $this->pass($data);
    }

    public function readRule()
    {
        $timestamp = $this->params['timestamp'] ?? 0;
        $chat_id = $this->params['chat_id'] ?? 0;
        $res = Db::name('config_personal')->where(['user_id'=>$this->member['id']])->update(['is_read_rule'=>1]);
        $msg = '阅读完成' . ($this->member['is_banned'] ? ',请等待到期解封' : '');
        if ($res) {
            if ($this->member['is_banned'] && strtotime($this->member['banned_end_time']) < time()) {
                Db::name('user')->where(['id'=>$this->member['id']])->update(['is_banned'=>0, 'banned_end_time'=>null]);
                $msg = '封号已解除';
            }
        }
        if ($chat_id) {
            $chat = Db::name('privatechat')->find($chat_id);
            if ($chat) {
                $chat_data = json_decode($chat['data'], true);
                if (!isset($chat_data['state']) || $chat_data['state'] == 0) {
                    $chat_data['state'] = 1;
                    Db::name('privatechat')->where(['id'=>$chat_id])->update(['data'=>json_encode($chat_data, JSON_UNESCAPED_UNICODE)]);
                }
            }
        }
        return $this->pass($msg);
    }


    public function user_device_accessibility()
    {
        $user_id = $this->member['id'];
        $device_id = $this->params['device_id'] ?? '';
        $device_info = $this->params['device_info'] ?? '';
        $accessibility = $this->params['accessibility'] ?? '';

        if (!$accessibility) return $this->pass('empty accessibility');
        if (!$user_id) return $this->pass('unlogin');
        $hasDevice = Db::name('user_device_accessibility')->where(['user_id'=>$user_id, 'device_id'=>$device_id])->find();
        if ($hasDevice) {
            Db::name('user_device_accessibility')->where(['id'=>$hasDevice['id']])->update(['device_info'=>$device_info, 'accessibility'=>$accessibility, 'update_time'=>time()]);
        } else {
            Db::name('user_device_accessibility')->insert(['user_id'=>$user_id, 'device_id'=>$device_id, 'device_info'=>$device_info, 'accessibility'=>$accessibility, 'create_time'=>time()]);
        }
    }

    public function getUserSysInfo()
    {
        $uid = $this->params['uid']??0;
        $timestamp = $this->params['timestamp']??0;

        // 用是否开启推送来判断用户是否在线
        $info = Db::name('user')->master()->where(['id'=>$uid])->field('id,is_online,last_login_datetime,unpush')->find();
        $sys = Db::name('user_repeat_check')->master()->where(['user_id'=>$uid])->value('os');

        $info['ios'] = strpos($sys, 'iPhone') != false;

        return $this->pass($info);
    }

    public function apply_un_black()
    {
        $touser_id = $this->params['touser_id'] ?? 0;

        $m_is_black = Blacklist::where(['user_id'=>$this->member['id'], 'to_user'=>$touser_id])->find();
        if ($m_is_black) return $this->miss('请先解除拉黑对方');
        
        $t_is_black = Blacklist::where(['to_user'=>$this->member['id'], 'user_id'=>$touser_id])->find();
        if (!$t_is_black) return $this->miss('对方未拉黑你');

        $apply = Db::name('apply_un_blacklist')->where(['user_id'=>$this->member['id'], 'touser_id'=>$touser_id])->find();
        if ($apply) {
            if ($apply['state'] == 0) {
                return $this->miss('已申请,等待对方审核');
            }
            Db::name('apply_un_blacklist')->delete($apply['id']);
        }

        $unblacklist_intimate = Db::name('config_system')->where(['title'=>'unblacklist_intimate'])->value('content');
        $couple = $touser_id<$this->member['id'] ? $touser_id.','.$this->member['id'] : $this->member['id'].','.$touser_id;
        $intimate = Db::name('user_intimate')->where(['couple_a' => $couple])->value('intimate');
        if ($unblacklist_intimate>$intimate) return $this->miss('亲密度不足,无法申请');

        $res = Db::name('apply_un_blacklist')->insert(['user_id'=>$this->member['id'], 'touser_id'=>$touser_id, 'time'=>time()]);

        $message = [
            'sys_channel' => getenv('APP_CHANNEL'),
            'type' => 32,
            'to_user' => $touser_id,
            'context' => json_encode([
                            'name' => $this->member['name'],
                            'head' => $this->member['head_portrait'],
                            'state'=>0
                        ], JSON_UNESCAPED_UNICODE),
            'uid' => $this->member['id'],
        ];

        Db::name('sys_message')->insert($message);

        if(sizeof(Gateway::getClientIdByUid(getenv('SOCKET_PREFIX') . $touser_id))){
            $url = request()->domain() . str_replace('/index.php', '', request()->baseFile()) . '/apis/home/privatechat/getreadcount';
            $datas = [
                'data'=>json_encode(['user_id'=>$touser_id])
            ];
            curl($url, json_encode($datas, JSON_UNESCAPED_UNICODE));
        }

        return $res ? $this->pass('已向对方发起申请') : $this->miss('申请失败,请稍后重试');
    }

    public function deal_apply_un_black()
    {
        // $this->member['id'] = 12;
        $sys_message_id = $this->params['sys_message_id'] ?? 0;
        $touser_id = $this->params['touser_id'] ?? 0;
        $state = $this->params['state'] ?? -1;

        $apply = Db::name('apply_un_blacklist')->where(['touser_id'=>$this->member['id'], 'user_id'=>$touser_id, 'state'=>0])->find();
        Db::name('sys_message')->where(['id'=>$sys_message_id, 'type'=>32, 'to_user'=>$this->member['id']])->delete();
        if (!$apply) return $this->pass('申请已处理');

        $res = Db::name('apply_un_blacklist')->where(['id'=>$apply['id']])->update(['state'=>$state]);
        if (!$res) return $this->miss('操作失败,请稍后重试');

        if ($state == 1) {
            $blackList = Blacklist::get([
                'user_id' => $this->member['id'],
                'to_user' => $touser_id,
            ]);
            Cache::rm('black' . $this->member['id'] . '_' . $touser_id);
            if ($blackList) {
                Blacklist::destroy($blackList->id);
            }
        }
        return $this->pass('操作成功');
    }
}